package request

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"sync"
	"time"

	"GK-app/logger" // 导入 logger 模块
)

var rateLimitedLogger = logger.NewRateLimitedLogger(5 * time.Second) // 每 10 秒限流

// PerformRequestsWithLogger 执行 GET 和 POST 请求，并使用带限流的日志记录
func PerformRequestsWithLogger(getURL, postURL string, dataToUpload []byte, wg *sync.WaitGroup) {
	// 异步下载
	go func() {
		defer wg.Done()
		resp, errSync := http.Get(getURL)
		if errSync != nil {
			rateLimitedLogger.LogWithRateLimit("GET 请求失败", errSync)
			fmt.Println("GET 请求失败:", errSync)
			return
		}
		body, _ := io.ReadAll(resp.Body)
		err := resp.Body.Close()
		if err != nil {
			rateLimitedLogger.LogWithRateLimit("读取 GET 响应失败", err)
			fmt.Println("读取 GET 响应失败:", err)
			return
		}
		fmt.Printf("Downloaded %.2f KB\n", float64(len(body))/1024)
	}()

	// 异步上传
	go func() {
		defer wg.Done()
		resp, errSync := http.Post(postURL, "application/octet-stream", bytes.NewBuffer(dataToUpload))
		if errSync != nil {
			rateLimitedLogger.LogWithRateLimit("POST 请求失败", errSync)
			fmt.Println("POST 请求失败:", errSync)
			return
		}
		err := resp.Body.Close()
		if err != nil {
			rateLimitedLogger.LogWithRateLimit("读取 POST 响应失败", err)
			fmt.Println("读取 POST 响应失败:", err)
			return
		}
		fmt.Printf("Uploaded %.2f KB\n", float64(len(dataToUpload))/1024)
	}()
}
